from django.http import HttpResponseRedirect,HttpResponse,HttpResponseNotFound
from django.views.generic.simple import direct_to_template
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.views.decorators.cache import never_cache
from forms import UploadFileForm
from django.conf import settings
from django.http import Http404
from models import File
import mimetypes
import os
from json import dumps as json_dumps
from django.shortcuts import get_object_or_404
from django.core.servers.basehttp import FileWrapper
from django.views.decorators.csrf import csrf_exempt

def Http403(request):
    response = direct_to_template(request,'403.html')
    response.status_code = 403
    return response

@csrf_exempt
@login_required
def upload(request,template_name="profile.html"):
    response = Http403(request)
    if request.method == 'POST':
        if int(request.POST['owner']) == request.user.pk:
            form = UploadFileForm(request.POST, request.FILES)
            if form.is_valid():
                f = form.save(commit=False)
                if not f.name: 
                    f.name = request.FILES['file'].name
                try:
                    f.save()
                except UnicodeEncodeError:
                    f.name = "safgf"
                    f.save()
            response = HttpResponseRedirect(request.META['HTTP_REFERER'])
    else:
        form = UploadFileForm( initial={'owner':request.user.pk} )
        response = direct_to_template(request,template_name, {'form': form,'files':File.objects.filter(owner=request.user).all()})

    return response

@never_cache
def download(request,uuid,file_name):
    try:
        f = File.objects.get(uuid=uuid)
    except:
        raise Http404

    if f.avalible is True:
        try:
            file_path = f.filepath()
#            fsock = FileWrapper(open(file_path,"r"))
            file_size = os.path.getsize(file_path)
            mime_type_guess = mimetypes.guess_type(file_name)
            if mime_type_guess is not None:
                response = HttpResponse()
                response['Content-Disposition'] = 'attachment; filename="' + file_name.encode('utf-8')+'"'
                response['Content-Length'] = file_size
                response['Content-Type'] = mime_type_guess[0]
                response['X-Accel-Redirect'] = settings.INTERNAL_DOWNLOAD_URL+f.file.name
            f.downloads += 1
            f.save()
        except IOError:
            response = HttpResponseNotFound()
        return response
    else:
        return Http403(request)

@login_required
def profile(request,template_name="profile.html"):
    files = File.objects.filter(owner=request.user).all()
    form = UploadFileForm( initial={'owner':request.user.pk} )
    return direct_to_template(request,template_name, {'files':files,'form':form})

@login_required
def allfiles(request,template_name="allfiles.html"):
    if request.user.is_superuser:
        files = File.objects.all()
        return direct_to_template(request,template_name, {'files':files})
    else:
        return Http403(request)


@login_required
def change_file_state(request, fileid):
    f = get_object_or_404(File, pk=fileid)
    if request.user.pk == f.owner.pk or request.user.is_superuser:
        if f.avalible is True:
            f.avalible = False
        else:
            f.avalible = True
        f.save()
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    else:
        return Http403(request)

@login_required
def delete_file(request, fileid):
    f = get_object_or_404(File, pk=fileid)
    if request.user.pk == f.owner.pk or request.user.is_superuser:
        f.delete()
        return HttpResponseRedirect(request.META['HTTP_REFERER'])
    else:
        return Http403(request)

@login_required
def get_file_downloads_count(request,fileid):
    f = get_object_or_404(File, pk=fileid)
    if request.user.pk == f.owner.pk or request.user.is_superuser:
        return HttpResponse(f.downloads)
    else:
        return Http403(request)

@login_required
def get_file_id_by_uuid(request,fileuuid):
    f = get_object_or_404(File, uuid=fileuuid)
    if request.user.pk == f.owner.pk or request.user.is_superuser:
        return HttpResponse(f.pk)
    else:
        return Http403(request)

@login_required
def get_file_uuid_by_id(request,fileid):
    f = get_object_or_404(File, pk=fileid)
    if request.user.pk == f.owner.pk or request.user.is_superuser:
        return HttpResponse(f.uuid)
    else:
        return Http403(request)




